<?php
namespace App\Controllers\Admin\System;

use App\Components\Admin\ResponseHelper;
use App\Components\Twig\Twig;
use App\Models\System\SystemUser;
use App\Models\System\SystemUserView;
use Exception;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * 管理后台界面设置
 */
class UserViewController
{
    /**
     * 界面设置
     */
    public function config(Request $request, Response $response)
    {
        $userId = SystemUser::getIdByToken();
        if ($userId <= 0) {
            throw new Exception('未登录');
        }

        $infoRs = SystemUserView::select('id', 'content')
            ->where('user_id', $userId)
            ->orderBy('id', 'asc')->first();
        if ($request->getMethod() == 'POST') {
            $params = $request->getParsedBody();
            $params = array_filter($params);
            !isset($params['main_view']) && $params['main_view'] = 'light';
            !isset($params['sidebar_view']) && $params['sidebar_view'] = 'gerneral';

            if (isset($infoRs->id)) {
                $updateRs = SystemUserView::where('id', $infoRs->id)
                    ->where('user_id', $userId)
                    ->update([
                        'content' => json_encode($params),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ]);
                if ($updateRs != 1) {
                    return ResponseHelper::error($response, '更新保存错误');
                }
            } else {
                $insertRs = SystemUserView::insert([
                    'user_id' => $userId,
                    'content' => json_encode($params),
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
                if ($insertRs != 1) {
                    return ResponseHelper::error($response, '保存错误');
                }
            }

            SystemUserView::clearVierCache($userId);

            return ResponseHelper::success($response);
        }
        if (isset($infoRs->id)) {
            $infoRs = json_decode($infoRs->content, true);
        }

        $view = Twig::fromRequest($request);
        $response->getBody()->write($view->fetch('admin/system/user_view/config.html', [
            'title' => '界面设置',
            'info' => $infoRs,
        ]));
        return $response;
    }
}
